package realestate.manager.object;

import realestate.entity.ObjectOnMapShort;
import realestate.entity.RealEstate;
import realestate.manager.request.IRequest;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Admin
 * Date: 12.04.11
 * Time: 18:01
 * To change this template use File | Settings | File Templates.
 */
public abstract class RequestManager<R extends RealEstate> implements IRAManager<R> {

	public abstract EntityManager getEntityManager();
	public abstract Class<R> getOperateClass();

	@Override
	public R getById(Long id) {
		return getEntityManager().find(getOperateClass(), id);
	}

	@Override
	public boolean remove(R object_to_remove) {
		if(object_to_remove != null)
			return remove(object_to_remove.getId());
		return false;
	}

	@Override
	public boolean remove(Long id) {
		R object_to_remove = getById(id);
		if(object_to_remove == null)
			return false;
		getEntityManager().remove(object_to_remove);
		getEntityManager().flush();
		return true;
	}

	@Override
	public R add(R new_object) {
		getEntityManager().persist(new_object);
		getEntityManager().flush();
		return new_object;
	}

	@Override
	public List<ObjectOnMapShort> getShortList(IRequest request, int zoom_level) {
		Query query = getEntityManager().createQuery(request.buildQueryString());
		return query.getResultList();
	}
}
